import React, { Component } from 'react'
import { BackTopWrapper } from './style'

class BackTop extends Component {
  constructor() {
    super()
    this.state = {
      flag: false
    }
  }
  render() {
    return (
      <div>
        {this.state.flag ? <BackTopWrapper onClick={() => { this._backTop() }}>
          <i className='sky-leaf'>&#xe623;</i>
        </BackTopWrapper> : null}
      </div>
    )
  }
  _backTop() {
    let scrollToptimer = setInterval(() => {
      let top = document.body.scrollTop || document.documentElement.scrollTop
      let speed = top / 4
      if (document.body.scrollTop !== 0) {
        document.body.scrollTop -= speed
      } else {
        document.documentElement.scrollTop -= speed
      }
      if (top === 0) {
        clearInterval(scrollToptimer)
      }
    }, 30)
  }
  componentDidMount() {
    this.bindEvent()
  }
  componentWillUnmount() {
    window.removeEventListener('scroll', () => { this.changeScrollTopShow() })
  }
  bindEvent() {
    window.addEventListener('scroll', () => { this.changeScrollTopShow() })
  }
  changeScrollTopShow() {
    let flag = document.documentElement.scrollTop > 300 ? true : false
    this.setState({ flag })
  }
}

export default BackTop
